package cn.dnf.basic.controller;

import cn.dnf.basic.util.FastDfsUtils;
import cn.dnf.basic.util.JsonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;

@RestController
@RequestMapping("/fastdfs")
public class FastDfsController {
    /**
     * 上传的接口
     * @return
     * restful：@RequestPart 接收的是文件
     * required = true:必须上传一个图片
     */
    @PostMapping
    public JsonResult upload(@RequestPart(value = "file",required = true) MultipartFile file) {
        try {
            //获取原始文件名称
            String originalFilename = file.getOriginalFilename();
            //获取文件的后缀，不要.
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //调用工具类中的upload方法
            String path = FastDfsUtils.upload(file.getBytes(), substring);
            //把path设置给jsonResult中的resultObj属性
            return JsonResult.me().setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("上传失败");
        }
    }

        /**
         * 删除的方法
         * /common/fastDfs/?path="+filePath @RequestParam
         * group1/M00/00/EC/CgAIC2LdBgCAXXWCAADdONORJAE198.jpg
         */
        @DeleteMapping
        public JsonResult delete (@RequestParam(value = "path", required = true) String path){
            try {
                //调用工具类中delete方法
                //group1/M00/00/EC/CgAIC2LdBgCAXXWCAADdONORJAE198.jpg
                //需要截取出来group1     M00/00/EC/CgAIC2LdBgCAXXWCAADdONORJAE198.jpg
                String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
                String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
                String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);//  M00/00/EC/CgAIC2LdBgCAXXWCAADdONORJAE198.jpg
                FastDfsUtils.delete(groupName,remotePath);
                return JsonResult.me();
            } catch (Exception e) {
                e.printStackTrace();
                return JsonResult.me().setMsg("删除失败");
            }



}}
